<template>
  <div>
    <el-form :model="rscLocation" label-width="160px">
        <el-form-item :label="$t('operations.rscName')">
          <span class="block">{{ chosenItem.id }}</span>
        </el-form-item>
        <el-form-item
          v-for="(node, level) in rscLocation"
          :key="level"
          :label="level"
        >
          <el-select
            v-model="rscLocation[level]"
            multiple
            @change="handleLocationChange($event)"
            @remove-tag="handleLocationRemoveTag"
             :placeholder="$t('common.pleaseSelect')"
          >
            <el-option
              v-for="item in nodeList"
              :key="item.id"
              :label="item.id"
              :value="item.id"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    <div class="dialog-footer">
      <el-button @click="handleClick">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="handleOk">{{ $t('common.confirm') }}</el-button>
    </div>
  </div>
</template>
<script>
import { updateLocations } from "@/api/resource";

export default {
  props: ['chosenItem', 'rscLocation', 'nodeList'],
  data() {
    return {

    }
  },
  methods: {
    handleLocationChange(node) {
      let arr = [...node];

      for (let i in arr) {
        for (let j in this.nodeList) {
          if (arr[i] == this.nodeList[j].id) {
            this.nodeList[j].disabled = true;
          }
        }
      }

      this.$forceUpdate(); //必须要有强制更新，必然检测不到选中的值
    },
    handleLocationRemoveTag(option) {
      for (let i in this.nodeList) {
        if (option == this.nodeList[i].id) {
          this.nodeList[i].disabled = false;
        }
      }
    },
    handleClick() {
      this.$emit('cancel')
    },
    handleOk() {
      let location = {};
      location.node_level = [];
      location.rsc_id = this.chosenItem.id;

      for (const key in this.rscLocation) {
        location[key] = this.rscLocation[key];
        if (this.rscLocation[key].length == 0) {
          continue;
        } else if (this.rscLocation[key].length >= 1) {
          for (const item of this.rscLocation[key]) {
            location.node_level.push({
              level: key,
              node: item,
            });
          }
        }
      }

      let id = this.chosenItem.id;
      let data = location;

      updateLocations({ id, data }).then(() => {
        this.$message.success("location update success");
        this.$emit('cancel');
      });
    },
  }
}


</script>
<style lang="scss" scoped></style>